package com.linkgie.galaxyframework.binaryserialize.impl;

import java.util.Base64;

import com.linkgie.galaxyframework.binaryserialize.DataOptions;
import com.linkgie.galaxyframework.utils.Base58Encoding;
import com.linkgie.galaxyframework.utils.BinaryUtils;
import com.linkgie.galaxyframework.utils.HexUtils;
import com.linkgie.galaxyframework.utils.TextEncoding;

import utils.io.BytesOutputBuffer;
import utils.io.BytesSlice;

public class StringValueConverter extends AbstractDynamicValueConverter {

	public StringValueConverter() {
		super(String.class);
	}

	@Override
	public Object decodeValue(BytesSlice dataSlice, DataOptions options) {
		// dataSlice.getString
		if (dataSlice.size() == 0) {
			return "";
		}
		byte[] bytes = dataSlice.getBytesCopy();

		if (options.getTextEncoding() == TextEncoding.BASE58) {
			return Base58Encoding.encode(bytes);
		} else if (options.getTextEncoding() == TextEncoding.BASE64) {
			return Base64.getEncoder().encodeToString(bytes);
		} else if (options.getTextEncoding() == TextEncoding.HEX) {
			return HexUtils.encode(bytes);
		} else if (options.getTextEncoding() == TextEncoding.CHARSET_UTF8) {
			return BinaryUtils.toString_UTF8(bytes);
		} else {
			throw new IllegalArgumentException("Unsupported Text Encoding: " + options.getTextEncoding() + "!");
		}
	}

	@Override
	public int encodeDynamicValue(Object value, BytesOutputBuffer buffer, DataOptions options) {
		byte[] bytes;
		if (value == null) {
			bytes = BinaryUtils.EMPTY_BYTES;
		} else if (options.getTextEncoding() == TextEncoding.BASE58) {
			bytes = Base58Encoding.decode((String) value);
		} else if (options.getTextEncoding() == TextEncoding.BASE64) {
			bytes = Base64.getDecoder().decode((String) value);
		} else if (options.getTextEncoding() == TextEncoding.HEX) {
			bytes = HexUtils.decode((String) value);
		} else if (options.getTextEncoding() == TextEncoding.CHARSET_UTF8) {
			bytes = BinaryUtils.toBytes_UTF8((String) value);
		} else {
			throw new IllegalArgumentException("Unsupported Text Encoding: " + options.getTextEncoding() + "!");
		}
		int size = bytes.length;
		size += writeSize(bytes.length, buffer);
		buffer.write(bytes);
		return size;
	}

}
